package com.rpoonolly.simplegame.core.aabb;

import javax.vecmath.Vector2d;

import com.rpoonolly.simplegame.core.CollisionDetector;
import com.rpoonolly.simplegame.core.CollisionResponder;


public class AABBCollisionManager implements CollisionDetector<AABBEntity, AABBCollision>, CollisionResponder<AABBCollision> {
	@Override
	public AABBCollision collisionDetect(AABBEntity statEntity, AABBEntity dynEntity, Vector2d v) {
		if (
			statEntity.getX() < dynEntity.getX() + dynEntity.width + v.x &&
			statEntity.getX() + statEntity.width > dynEntity.getX() + v.x &&
			statEntity.getY() < dynEntity.getY() + dynEntity.height + v.y &&
			statEntity.getY() + statEntity.height > dynEntity.getY() + v.y 
		) {
			return new AABBCollision(statEntity, dynEntity, v);
		}
		
		return null;
	}
	
	@Override
	public Vector2d collisionRespond(AABBCollision collision) {
		AABBCollisionSide direction = collision.getCollisionDirection();
		Vector2d corrected = new Vector2d();
		Vector2d slide = new Vector2d();
		
		slide.set(collision.getMovementVector());
		slide.scale(1 - collision.getCollisionTime());
		if (direction == AABBCollisionSide.LEFT || direction == AABBCollisionSide.RIGHT) {
			slide.x = 0;
		} else {
			slide.y = 0;
		}
		
		corrected.set(collision.getMovementVector());
		corrected.scale(collision.getCollisionTime());
		corrected.add(slide);
		roundVector(corrected);
		
		return corrected;
	}
	
	private void roundVector(Vector2d v) {
		v.x = (v.x >= 0) ? Math.floor(v.x) : Math.ceil(v.x);
		v.y = (v.y >= 0) ? Math.floor(v.y) : Math.ceil(v.y);
	}
}
